<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/08/28
 * Desc: 全局搜索
 */
class Model_Api_V2_Global_Search extends ORM
{


    /**
     * @function
     * @param $seachkeys 分词结果
     * @param $keyword 搜索的词
     * @param $is_mobile 是否是手机
     */
    public static function get_search_model($seachkeys,$keyword,$typeid,$startcity=null)
    {
        $out = array();
        $has_search = array();

        //手机端模型
        $search_model = Model_Model::get_wap_search_model();
        $out['all_search_model'] = $search_model;
        foreach ($search_model as $m)
        {
            //如果不是当前搜索的模块，那么判断是否含有搜索结果
            if($typeid!=$m['typeid'])
            {

                $model = Model_Model::get_module_info($m['typeid']);
                if(!$model['maintable'])
                {
                    continue ;
                }

                $keysearch = !empty($seachkeys) && !empty($seachkeys[0])? self::get_keyword_where($model['maintable'],$seachkeys,array('keyword'=>$keyword)):'';

                // var_dump($keysearch);die;
                $where = self::_get_default_where(array('keyword'=>$keyword),$keysearch,$model['maintable']);


                if(self::check_column($model['maintable'],'ishidden')) {
                    $where .= " and ishidden=0 ";
                }
                if($model['maintable']=='model_archive')
                {
                    $where .=" and a.typeid={$m['typeid']}";
                }
                if($m['typeid']==11)
                {
                    $where .= " and a.status=1";
                }
                if(!empty($startcity) )
                {

                    if(!self::check_column($model['maintable'],'startcity'))
                    {
                        continue;
                    }
                    $startcity_id = DB::select('id')->from('startplace')->where('cityname','=',$startcity)->execute()->get('id');
                    if(!empty($startcity_id))
                    {
                        $where .= " and a.startcity='{$startcity_id}'";
                    }
                }



                if($model['maintable'])
                {
                    $table = 'sline_'.$model['maintable'];
                    $sql = "select a.id from $table as a WHERE  $where limit 1";
                    $list = DB::query(1,$sql)->execute()->as_array();
                    if($list)
                    {
                        $has_search[] = $m;
                    }
                }

            }
            else
            {
                $has_search[] = $m;
            }
        }
        $out['has_search'] = $has_search;
        return $out;
    }


    /**
     * 获取默认的搜索条件 关键词，目的地，属性
     * @function
     */
    private static function _get_default_where($params,$keysearch,$table)
    {
        $where = " a.id>0";
        //关键词
        if($keysearch)
        {
            $where .= " and ($keysearch)";
        }

        $cfg_city_site_type = Model_Sysconfig::get_configs(0, 'cfg_city_site_type', true);
        $city = Cookie::get('current_city', '选择城市');
        if(!empty($city))
        {
            //如果是出发地
            if($cfg_city_site_type==1  && self::check_column($table,'startcity'))
            {
                $startcity_id = DB::select('id')->from('startplace')->where('cityname', '=', $city)->execute()->get('id');
                if (!empty($startcity_id))
                {
                    $where .= " and a.startcity='{$startcity_id}'";
                }
            }
            else if($cfg_city_site_type!=1)
            {
                $destid  = DB::select('id')->from('destinations')->where('kindname', '=', $city)->execute()->get('id');
                if($destid&&self::check_column($table,'kindlist'))
                {
                    $where .= " and find_in_set($destid,a.kindlist)";
                }
            }
        }

        //目的地
        if($params['destid']&&self::check_column($table,'kindlist'))
        {
            $where .= " and find_in_set({$params['destid']},a.kindlist)";
        }
        //属性
        if(self::check_column($table,'attrid'))
        {
            foreach ($params['attrlist'] as $attr)
            {
                if($attr)
                {
                    $where .=" and find_in_set($attr,a.attrid)";
                }
            }
        }
        return $where;
    }

    /**
     * @function 解析关键词
     * @param $table
     * @param $keyword
     * @return string
     */
    private static function get_keyword_where($table,$keyword,$params)
    {
        if(empty($keyword))
        {
            return '';
        }
        //过滤特殊字符,防止注入和报错
        $regex = "/\/|\~|\"|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
        $keyword = preg_replace($regex,"",$keyword);
        $keysearch = '';
        $add_column = self::get_add_column($table);
        //关键字
//        $keyword[] = $params['keyword'];
        $params_keyword=preg_replace($regex,"",$params['keyword']);
        if($params_keyword)
        {
            $keyword[] = $params_keyword;
        }
        if (preg_match("/^\d*$/", $keyword[0])) {
            $production_id = Common::getKeyword($keyword[0]);
            $keysearch = " a.id={$production_id} or ";
            //    return $keysearch;
        }
        $keyword = implode('|',$keyword);
        if($keyword)
        {
            $keysearch .= "a.title REGEXP '$keyword'";
            if($add_column)
            {
                $keysearch .=" or a.$add_column REGEXP '$keyword' ";
            }
        }
        return $keysearch;
    }

    /**
     * @function 获取扩展搜索字段
     * @param $table
     */
    private static function get_add_column($table)
    {
        $default_column = array('sellpoint', 'description');
        foreach ($default_column as $column)
        {
            if(self::check_column($table,$column))
            {
                return $column;
            }

        }

    }


    /**
     * @function 判断字段是否存在
     * @param $tabel
     * @param $column
     */
    private static function check_column($tabel,$column)
    {
        $tabel = 'sline_'.$tabel;
        $sql = "show columns from `{$tabel}` like '{$column}'";
        $result = DB::query(1,$sql)->execute()->current();
        if (false === $result)
        {
            return false;
        }
        else
        {
            return count($result) > 0 ? true : false;
        }

    }
}